import React, { Component } from "react";
import usermodel from "./usercontorlmodel/usermodel";
import Userinfos from "../usercontorl/server/Userinfos";
import UserContent from "./UserContent";
import AddUser from "./AddUser";
import Search from "./usercontorlmodel/Search";
interface Istate {
  list: Array<usermodel>;
}
export default class Usercontorl extends Component<any, Istate> {
  constructor(Props: any) {
    super(Props);
    this.state = {
        list: [],
    };
  }
  componentDidMount = async () => {//挂载时请求数据
   if(!this.state.list.length){
    let { data } = await Userinfos.query({});
    this.setState({
      list: data,
    });
   }
  //  console.log(this.props.lists);
   
  };
  del = async (id: number) => {//删除数据
    await Userinfos.del(id);
    this.setState({
      list: this.state.list.filter((item) => item.id !== id),
    });
  };
  add=async(item:usermodel)=>{//添加数据
    if(item.password!==''&&item.username!==""){
        let {data}=await Userinfos.post(item)
         this.setState({
            list:[...this.state.list,data]
         })        
      }else{
        alert('输入错误')
      }
    }
  
  search=async(key:string)=>{//搜索数据
    let { data } = await Userinfos.query({
        q:key
    });
    this.setState({
      list: data,
    });
  }
  render() {
    return (
      <>
        <h1>用户管理</h1>
       <Search search={this.search}></Search>
        <hr/>
        <AddUser add={this.add}></AddUser>
        <div className="table">
          <div className="tr">
            <div className="td">
              <div>编号</div>
              <div>用户名</div>
              <div>密码</div>
              <div>操作</div>
            </div>
          </div>
        <UserContent list={this.state.list} del={this.del}></UserContent>
        </div>
        </>
    );
  }
}

